package cn.com.anypay.manager.miaoma.suantaiqrcode.handler.impl;

import cn.com.anypay.manager.common.utils.HtmlUtils;
import cn.com.anypay.manager.miaoma.suantaiqrcode.SuantaiQrcodeEntity;
import cn.com.anypay.manager.miaoma.suantaiqrcode.handler.AbstractQrCodeHandler;
import cn.com.anypay.manager.miaoma.suantaiqrcode.dto.QrCodeGatewayResponse;
import cn.com.anypay.manager.common.response.ApiResponse;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * 在线图片类型二维码处理器 (type = 6)
 *
 * 处理在线图片展示，支持：
 * - 图片URL展示
 * - 标题和描述显示
 * - 长按识别二维码提示
 * - 响应式设计
 */
@Slf4j
@Component
public class ImageQrCodeHandler extends AbstractQrCodeHandler {

    private static final Integer SUPPORTED_TYPE = 6;
    private static final String HANDLER_NAME = "ImageQrCodeHandler";

    @Value("${suantai.qrcode.base-url:http://localhost:8080}")
    private String baseUrl;

    @Override
    public ApiResponse<Object> handle(SuantaiQrcodeEntity qrcode, String id) {
        logHandleStart(id);

        if (!isValidContent(qrcode.getContent())) {
            logHandleComplete(id, "Content is empty");
            return createErrorResponse(HttpStatus.BAD_REQUEST, "Content is empty");
        }

        JsonNode content = parseJsonContent(qrcode.getContent());
        if (content == null) {
            logHandleComplete(id, "Failed to parse JSON content");
            return createErrorResponse(HttpStatus.BAD_REQUEST, "Invalid JSON content");
        }

        String imageUrl = extractImageUrl(content);
        if (imageUrl == null || imageUrl.trim().isEmpty()) {
            logHandleComplete(id, "No image URL found");
            return createErrorResponse(HttpStatus.BAD_REQUEST, "No image URL found");
        }

        // 生成显示图片的页面URL
        String displayUrl = generateImageDisplayUrl(imageUrl, qrcode.getQrCodeName(), qrcode.getDescription());

        logHandleComplete(id, "Redirecting to image display page");
        return createRedirectResponse(displayUrl);
    }

    /**
     * 从JSON内容中提取图片URL
     *
     * @param content JSON内容
     * @return 图片URL
     */
    private String extractImageUrl(JsonNode content) {
        JsonNode urlNode = content.get("url");
        return urlNode != null ? urlNode.asText() : null;
    }

    /**
     * 生成显示图片的页面URL
     *
     * @param imageUrl 图片URL
     * @param title 标题
     * @param description 描述
     * @return 显示页面的URL
     */
    private String generateImageDisplayUrl(String imageUrl, String title, String description) {
        try {
            // 使用相对路径，让浏览器自动处理域名和端口
            String fullUrl = "/api/anon/image-display?" +
                    "imageUrl=" + URLEncoder.encode(imageUrl, StandardCharsets.UTF_8) +
                    "&title=" + URLEncoder.encode(title != null ? title : "", StandardCharsets.UTF_8) +
                    "&description=" + URLEncoder.encode(description != null ? description : "", StandardCharsets.UTF_8);

            log.info("Generated image display URL: {}", fullUrl);
            return fullUrl;

        } catch (Exception e) {
            log.error("Error generating image display URL", e);
            // 降级处理：返回相对路径
            return "/api/anon/image-display?" +
                    "imageUrl=" + URLEncoder.encode(imageUrl, StandardCharsets.UTF_8) +
                    "&title=" + URLEncoder.encode(title != null ? title : "", StandardCharsets.UTF_8) +
                    "&description=" + URLEncoder.encode(description != null ? description : "", StandardCharsets.UTF_8);
        }
    }

    @Override
    public Integer getSupportedType() {
        return SUPPORTED_TYPE;
    }

    @Override
    public String getHandlerName() {
        return HANDLER_NAME;
    }

    @Override
    public ApiResponse<Object> handleForGateway(SuantaiQrcodeEntity qrcode, String id) {
        logHandleStart(id);

        if (!isValidContent(qrcode.getContent())) {
            logHandleComplete(id, "Content is empty");
            return createErrorResponse(HttpStatus.BAD_REQUEST, "Content is empty");
        }

        JsonNode content = parseJsonContent(qrcode.getContent());
        if (content == null) {
            logHandleComplete(id, "Failed to parse JSON content");
            return createErrorResponse(HttpStatus.BAD_REQUEST, "Invalid JSON content");
        }

        String imageUrl = extractImageUrl(content);
        if (imageUrl == null || imageUrl.trim().isEmpty()) {
            logHandleComplete(id, "No image URL found");
            return createErrorResponse(HttpStatus.BAD_REQUEST, "No image URL found");
        }

        // 为网关模式返回结构化数据
        logHandleComplete(id, "Preparing image display data for gateway");
        return createGatewayDisplayResponse(
            qrcode.getQrCodeId(),
            qrcode.getQrCodeName(),
            qrcode.getQrCodeType(),
            QrCodeGatewayResponse.DisplayType.IMAGE,
            imageUrl,
            qrcode.getQrCodeName(),
            qrcode.getDescription()
        );
    }
}